<script setup lang="ts">
import { ref, computed, onMounted, watch } from 'vue';
import { useQuasar } from 'quasar';
import { useUserStore } from '../stores/user';
import PracticeDetail from './PracticeDetail.vue';

const $q = useQuasar();
const userStore = useUserStore();

// 练习记录接口
interface PracticeRecord {
  id: number;
  practice_date: string;
  total_problems: number;
  correct_count: number;
  accuracy: number;
  total_time: number;
  details: Array<{
    problem: {
      expression: string;
      answer: number;
      displayExpression: string;
    };
    userAnswer: string;
    isCorrect: boolean;
    timeSpent: number;
  }>;
}

// 练习记录
const practiceRecords = ref<PracticeRecord[]>([]);
// 错题集合
const wrongProblems = ref<any[]>([]);

// 添加练习详情对话框的状态
const showPracticeDetailDialog = ref(false);
const currentPracticeDetail = ref<PracticeRecord | null>(null);

// 添加耗时分析相关的状态
const sortByTime = ref(false);
const highlightLongTime = ref(true);
const longTimeThreshold = ref(6); // 默认6秒

// 提速练习相关状态
const speedUpTab = ref('overview');
const showSpeedUpDialog = ref(false);
const speedUpProblemCount = ref(10); // 默认生成10道题

// 超时题目接口
interface LongTimeProblem {
  expression: string;
  correctAnswer: number;
  timeSpent: number;
  practiceDate: string;
  isCorrect: boolean;
}

const longTimeProblems = ref<LongTimeProblem[]>([]);

// 初始化时从服务器加载数据
onMounted(async () => {
  try {
    await loadPracticeRecords();
    // 从练习记录中提取错题
    extractWrongProblems();
    // 提取超时题目
    extractLongTimeProblems();
  } catch (error) {
    console.error('加载数据失败:', error);
    $q.notify({
      message: '加载数据失败',
      color: 'negative'
    });
  }
});

// 加载练习记录
const loadPracticeRecords = async () => {
  try {
    const response = await fetch(`${import.meta.env.VITE_API_BASE_URL}/api/practice/records`, {
      headers: {
        'Authorization': `Bearer ${localStorage.getItem('token')}`
      }
    });
    
    const data = await response.json();
    if (data.success) {
      // 解析每个记录的details字段，并确保total_time和accuracy是数字
      practiceRecords.value = data.data.map((record: any) => ({
        ...record,
        details: JSON.parse(record.details),
        total_time: parseFloat(record.total_time),
        accuracy: parseFloat(record.accuracy)
      }));
    } else {
      throw new Error(data.message);
    }
  } catch (error) {
    console.error('获取练习记录失败:', error);
    throw error;
  }
};

// 从练习记录中提取错题
const extractWrongProblems = () => {
  const wrongs = new Set();
  practiceRecords.value.forEach(record => {
    record.details.forEach(detail => {
      if (!detail.isCorrect) {
        wrongs.add({
          expression: detail.problem.displayExpression,
          studentAnswer: detail.userAnswer,
          correctAnswer: detail.problem.answer,
          practiceDate: record.practice_date
        });
      }
    });
  });
  wrongProblems.value = Array.from(wrongs);
};

// 提取超时题目
const extractLongTimeProblems = () => {
  const longTimeSet = new Set<LongTimeProblem>();
  practiceRecords.value.forEach(record => {
    record.details.forEach(detail => {
      if (detail.timeSpent > longTimeThreshold.value) {
        longTimeSet.add({
          expression: detail.problem.displayExpression,
          correctAnswer: detail.problem.answer,
          timeSpent: detail.timeSpent,
          practiceDate: record.practice_date,
          isCorrect: detail.isCorrect
        });
      }
    });
  });
  // 按耗时从长到短排序
  longTimeProblems.value = Array.from(longTimeSet).sort((a, b) => b.timeSpent - a.timeSpent);
};

// 计算总体正确率
const overallAccuracy = computed(() => {
  if (practiceRecords.value.length === 0) return 0;
  
  let totalCorrect = 0;
  let totalProblems = 0;
  
  practiceRecords.value.forEach(record => {
    totalCorrect += record.correct_count;
    totalProblems += record.total_problems;
  });
  
  return totalProblems > 0 ? (totalCorrect / totalProblems) * 100 : 0;
});

// 按日期分组的练习数据
const practiceByDate = computed(() => {
  return practiceRecords.value.map(record => ({
    date: new Date(record.practice_date).toLocaleDateString(),
    accuracy: record.accuracy
  })).sort((a, b) => new Date(a.date).getTime() - new Date(b.date).getTime());
});

// 计算平均耗时
const averageTime = computed(() => {
  if (!currentPracticeDetail.value) return 0;
  const total = currentPracticeDetail.value.details.reduce((sum, detail) => sum + detail.timeSpent, 0);
  return total / currentPracticeDetail.value.details.length;
});

// 计算最长耗时
const maxTime = computed(() => {
  if (!currentPracticeDetail.value) return 0;
  return Math.max(...currentPracticeDetail.value.details.map(detail => detail.timeSpent));
});

// 按耗时排序的答题记录
const sortedDetails = computed(() => {
  if (!currentPracticeDetail.value) return [];
  
  const details = currentPracticeDetail.value.details.map((detail, index) => ({
    ...detail,
    index: index + 1
  }));
  
  if (sortByTime.value) {
    return [...details].sort((a, b) => b.timeSpent - a.timeSpent);
  }
  return details;
});

// 生成耗时分布数据
const timeDistribution = computed(() => {
  if (!currentPracticeDetail.value) return new Array(10).fill(0);
  
  const distribution = new Array(10).fill(0); // 0-1s, 1-2s, ..., 9-10s, >10s
  const maxTime = 10; // 最大显示10秒
  
  currentPracticeDetail.value.details.forEach(detail => {
    const time = Math.min(detail.timeSpent, maxTime);
    const index = Math.floor(time);
    distribution[index]++;
  });
  
  return distribution;
});

// 清除所有数据
const clearAllData = () => {
  $q.dialog({
    title: '确认',
    message: '确定要清除所有学习记录和错题集吗？此操作不可恢复。',
    cancel: true,
    persistent: true
  }).onOk(() => {
    wrongProblems.value = [];
    practiceRecords.value = [];
    
    $q.notify({
      message: '所有数据已清除',
      color: 'info'
    });
  });
};

// 删除特定错题
const removeWrongProblem = (index: number) => {
  wrongProblems.value.splice(index, 1);
  
  $q.notify({
    message: '已从错题集移除',
    color: 'positive'
  });
};

// 生成错题专项练习
const generatePracticeFromWrongs = () => {
  if (wrongProblems.value.length === 0) {
    $q.notify({
      message: '错题集为空，无法生成练习',
      color: 'warning'
    });
    return;
  }
  
  $q.notify({
    message: `已为您生成包含 ${wrongProblems.value.length} 道错题的专项练习`,
    color: 'positive'
  });
  
  // 实际实现中，这里可以跳转到练习生成页面并预填充题目
};

// 生成提速专项练习
const generateSpeedUpPractice = () => {
  if (longTimeProblems.value.length === 0) {
    $q.notify({
      message: '暂无超时题目，无法生成提速练习',
      color: 'warning'
    });
    return;
  }
  
  if (speedUpProblemCount.value <= 0 || speedUpProblemCount.value > longTimeProblems.value.length) {
    $q.notify({
      message: `请输入1-${longTimeProblems.value.length}之间的题数`,
      color: 'warning'
    });
    return;
  }
  
  // 选择指定数量的超时题目（按耗时排序）
  const selectedProblems = longTimeProblems.value.slice(0, speedUpProblemCount.value);
  
  $q.notify({
    message: `已为您生成包含 ${speedUpProblemCount.value} 道提速题目的专项练习`,
    color: 'positive'
  });
  
  // 实际实现中，这里可以跳转到练习生成页面并预填充题目
  console.log('提速练习题目:', selectedProblems);
};

// 查看练习详情
const viewPracticeDetail = (record: PracticeRecord) => {
  currentPracticeDetail.value = record;
  showPracticeDetailDialog.value = true;
};

// 监听阈值变化，自动重新分析超时题目
watch(longTimeThreshold, () => {
  extractLongTimeProblems();
});
</script>

<template>
  <q-card flat bordered>
    <q-card-section class="text-h6">
      学习分析系统
    </q-card-section>
    
    <q-tabs
      v-model="tab"
      dense
      class="text-grey"
      active-color="primary"
      indicator-color="primary"
      align="justify"
      narrow-indicator
    >
      <q-tab name="overview" label="学习概览" />
      <q-tab name="wrongs" label="错题集" />
      <q-tab name="speedup" label="提速练习" />
    </q-tabs>
    
    <q-separator />
    
    <q-tab-panels v-model="tab" animated>
      <!-- 学习概览面板 -->
      <q-tab-panel name="overview">
        <div class="row q-col-gutter-md">
          <!-- 学习统计卡片 -->
          <div class="col-md-4 col-sm-6 col-xs-12">
            <q-card class="bg-primary text-white">
              <q-card-section>
                <div class="text-h6">总体正确率</div>
                <div class="text-h3 text-center">{{ Math.round(overallAccuracy) }}%</div>
              </q-card-section>
            </q-card>
          </div>
          
          <div class="col-md-4 col-sm-6 col-xs-12">
            <q-card class="bg-secondary text-white">
              <q-card-section>
                <div class="text-h6">练习次数</div>
                <div class="text-h3 text-center">{{ practiceRecords.length }}</div>
              </q-card-section>
            </q-card>
          </div>
          
          <div class="col-md-3 col-sm-6 col-xs-12">
            <q-card class="bg-accent text-white">
              <q-card-section>
                <div class="text-h6">错题数量</div>
                <div class="text-h3 text-center">{{ wrongProblems.length }}</div>
              </q-card-section>
            </q-card>
          </div>
          
          <div class="col-md-3 col-sm-6 col-xs-12">
            <q-card class="bg-info text-white">
              <q-card-section>
                <div class="text-h6">超时题目</div>
                <div class="text-h3 text-center">{{ longTimeProblems.length }}</div>
                <div class="text-caption">超过{{ longTimeThreshold }}秒</div>
              </q-card-section>
            </q-card>
          </div>
        </div>
        
        <!-- 趋势图 -->
        <div class="q-mt-md">
          <div class="text-subtitle1 q-mb-sm">正确率趋势</div>
          <div class="accuracy-chart">
            <div 
              v-for="(record, index) in practiceByDate" 
              :key="index"
              class="chart-bar"
              :style="{ height: `${record.accuracy}%` }"
              :class="{ 'low-accuracy': record.accuracy < 60 }"
            >
              <q-tooltip>
                {{ record.date }}: {{ Math.round(record.accuracy) }}%
              </q-tooltip>
            </div>
          </div>
          <div class="chart-labels">
            <div 
              v-for="(record, index) in practiceByDate" 
              :key="index"
              class="chart-label"
            >
              {{ new Date(record.date).getDate() }}
            </div>
          </div>
        </div>
        
        <!-- 练习历史记录 -->
        <div class="q-mt-lg">
          <div class="text-subtitle1">练习记录</div>
          <q-list bordered separator>
            <q-item v-for="record in practiceRecords.slice(0, 5)" :key="record.id">
              <q-item-section>
                <q-item-label>{{ new Date(record.practice_date).toLocaleString() }}</q-item-label>
                <q-item-label caption>
                  正确率: {{ Math.round(record.accuracy) }}%
                  ({{ record.correct_count }}/{{ record.total_problems }})
                </q-item-label>
              </q-item-section>
              <q-item-section side>
                <div class="row items-center">
                  <q-badge 
                    :color="record.accuracy >= 80 ? 'positive' : 'warning'"
                    class="q-mr-sm"
                  >
                    {{ record.correct_count }}/{{ record.total_problems }}
                  </q-badge>
                  <q-btn
                    flat
                    round
                    dense
                    icon="visibility"
                    color="primary"
                    @click="viewPracticeDetail(record)"
                  >
                    <q-tooltip>查看详情</q-tooltip>
                  </q-btn>
                </div>
              </q-item-section>
            </q-item>
          </q-list>
        </div>
      </q-tab-panel>
      
      <!-- 错题集面板 -->
      <q-tab-panel name="wrongs">
        <div class="row q-gutter-md q-mb-md">
          <q-btn 
            color="primary" 
            icon="fitness_center" 
            label="生成错题专项练习" 
            @click="generatePracticeFromWrongs"
            :disable="wrongProblems.length === 0"
          />
          <q-btn 
            outline 
            color="negative" 
            icon="delete_sweep" 
            label="清空错题集" 
            @click="clearAllData"
            :disable="wrongProblems.length === 0"
          />
        </div>
        
        <div v-if="wrongProblems.length === 0" class="text-grey text-center q-pa-xl">
          <q-icon name="check_circle" size="48px" color="positive" />
          <div class="q-mt-sm">暂无错题记录，继续保持！</div>
        </div>
        
        <q-list bordered separator v-else>
          <q-item v-for="(problem, index) in wrongProblems" :key="index">
            <q-item-section>
              <q-item-label>{{ problem.expression }}</q-item-label>
              <q-item-label caption>
                你的答案: {{ problem.studentAnswer }} | 
                正确答案: {{ problem.correctAnswer }}
                <br>
                练习时间: {{ new Date(problem.practiceDate).toLocaleString() }}
              </q-item-label>
            </q-item-section>
            <q-item-section side>
              <q-btn 
                flat 
                round 
                icon="delete" 
                color="negative" 
                @click.stop="removeWrongProblem(index)" 
              />
            </q-item-section>
          </q-item>
        </q-list>
      </q-tab-panel>
      
      <!-- 提速练习面板 -->
      <q-tab-panel name="speedup">
        <div class="row q-gutter-md q-mb-md">
          <div class="col-12">
            <div class="row q-gutter-md items-center">
              <div class="col-auto">
                <q-input
                  v-model.number="longTimeThreshold"
                  type="number"
                  label="超时阈值（秒）"
                  min="1"
                  max="30"
                  style="width: 120px"
                  dense
                />
              </div>
              <div class="col-auto">
                <q-btn 
                  color="info" 
                  icon="refresh" 
                  label="重新分析" 
                  @click="extractLongTimeProblems"
                  dense
                />
              </div>
            </div>
          </div>
        </div>
        
        <div class="row q-gutter-md q-mb-md">
          <div class="col-12">
            <div class="row q-gutter-md items-center">
              <div class="col-auto">
                <q-input
                  v-model.number="speedUpProblemCount"
                  type="number"
                  label="生成题数"
                  min="1"
                  :max="longTimeProblems.length"
                  style="width: 120px"
                  dense
                />
              </div>
              <div class="col-auto">
                <q-btn 
                  color="primary" 
                  icon="fitness_center" 
                  label="生成提速专项练习" 
                  @click="generateSpeedUpPractice"
                  :disable="longTimeProblems.length === 0"
                  dense
                />
              </div>
            </div>
          </div>
        </div>
        
        <div v-if="longTimeProblems.length === 0" class="text-grey text-center q-pa-xl">
          <q-icon name="speed" size="48px" color="info" />
          <div class="q-mt-sm">暂无超时题目，继续保持！</div>
        </div>
        
        <div v-else class="q-mb-md">
          <div class="text-subtitle2 q-mb-sm">
            发现 {{ longTimeProblems.length }} 道超时题目（超过 {{ longTimeThreshold }} 秒）
          </div>
        </div>
        
        <q-list bordered separator v-if="longTimeProblems.length > 0">
          <q-item v-for="(problem, index) in longTimeProblems" :key="index">
            <q-item-section>
              <q-item-label>{{ problem.expression }}</q-item-label>
              <q-item-label caption>
                正确答案: {{ problem.correctAnswer }} | 
                耗时: {{ problem.timeSpent.toFixed(1) }}秒
                <br>
                练习时间: {{ new Date(problem.practiceDate).toLocaleString() }} |
                状态: <q-badge :color="problem.isCorrect ? 'positive' : 'negative'" :label="problem.isCorrect ? '正确' : '错误'" />
              </q-item-label>
            </q-item-section>
            <q-item-section side>
              <q-chip 
                :color="problem.timeSpent > longTimeThreshold * 1.5 ? 'negative' : 'warning'"
                text-color="white"
                dense
              >
                {{ problem.timeSpent.toFixed(1) }}s
              </q-chip>
            </q-item-section>
          </q-item>
        </q-list>
      </q-tab-panel>
    </q-tab-panels>

    <!-- 练习详情对话框 -->
    <q-dialog v-model="showPracticeDetailDialog" persistent>
      <q-card style="min-width: 350px; max-width: 800px">
        <q-card-section class="row items-center">
          <div class="text-h6">练习详情</div>
          <q-space />
          <q-btn icon="close" flat round dense v-close-popup />
        </q-card-section>

        <q-card-section v-if="currentPracticeDetail">
          <PracticeDetail
            :details="currentPracticeDetail.details"
            :total-problems="currentPracticeDetail.total_problems"
            :practice-date="currentPracticeDetail.practice_date"
            :accuracy="currentPracticeDetail.accuracy"
            :total-time="currentPracticeDetail.total_time"
          />
        </q-card-section>

        <q-card-actions align="right">
          <q-btn flat label="关闭" color="primary" v-close-popup />
        </q-card-actions>
      </q-card>
    </q-dialog>
  </q-card>
</template>

<script lang="ts">
export default {
  data() {
    return {
      tab: 'overview'
    };
  }
};
</script>

<style scoped>
.accuracy-chart {
  display: flex;
  align-items: flex-end;
  height: 200px;
  gap: 4px;
  margin-bottom: 4px;
  padding-top: 20px;
  border-left: 1px solid #ddd;
  border-bottom: 1px solid #ddd;
  box-sizing: border-box;
}

.chart-bar {
  flex: 1;
  background-color: #1976D2;
  margin: 0 3px;
  border-top-left-radius: 4px;
  border-top-right-radius: 4px;
  min-height: 4px;
  transition: height 0.3s;
}

.low-accuracy {
  background-color: #C10015;
}

.chart-labels {
  display: flex;
  justify-content: space-around;
}

.chart-label {
  flex: 1;
  text-align: center;
  font-size: 12px;
  color: #666;
}

.time-distribution-chart {
  display: flex;
  align-items: flex-end;
  height: 200px;
  gap: 4px;
  margin-bottom: 4px;
  padding-top: 20px;
  border-left: 1px solid #ddd;
  border-bottom: 1px solid #ddd;
  box-sizing: border-box;
}

.chart-bar {
  flex: 1;
  background-color: #1976D2;
  margin: 0 3px;
  border-top-left-radius: 4px;
  border-top-right-radius: 4px;
  min-height: 4px;
  transition: height 0.3s;
}

.chart-labels {
  display: flex;
  justify-content: space-around;
}

.chart-label {
  flex: 1;
  text-align: center;
  font-size: 12px;
  color: #666;
}

.long-time {
  background-color: rgba(255, 0, 0, 0.1);
}
</style> 